package com.shuzi.MediaShare.download;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.Handler;
import android.util.Log;

import com.shuzi.MediaShare.utils.Logger;
import com.shuzi.MediaShare.utils.StringUtils;
import com.shuzi.MediaShare.utils.Util;

/**
 * 下载任务
 * 
 * @author lung 下午2:28:38 2013
 */
public class DownloadTask implements Runnable
{

	private DownloadInfo info;

	private DownloadManager downloadManager;

	private long downloadSize = 0;// 已经下载好的大小

	private long lastDownloadSize = 0;// 到上一次下载的总大小

	private int totalSize;// 文件总大小

	private Logger logger;

	private Handler handler;

	private boolean isCancel = false;

	public DownloadTask(DownloadInfo info, DownloadManager downloadManager)
	{
		this.downloadManager = downloadManager;
		this.info = info;
		logger = Logger.getLogger();
		handler = new Handler();
	}

	public boolean isCancel()
	{
		return isCancel;
	}

	public void setCancel(boolean isCancel)
	{
		this.isCancel = isCancel;
	}

	@SuppressWarnings("resource")
	@Override
	public void run()
	{
		// 检测有没有存在下载好的视频
		File oldFile = new File(downloadManager.getBasePath(), info.getName()
				+ "." + info.getDownloadType());
		if (oldFile.exists())
		{
			Log.v("lung", "已经下载好");
			info.setState(DownloadInfo.STATE_FINISH);
			info.setTotleSize(StringUtils.bytes2kb(oldFile.length()));
			info.setHadDownloadSize(StringUtils.bytes2kb(oldFile.length()));
			info.setDownloadPercent(100);
			downloadManager.notifyDownloadStateEvent(DownloadInfo.STATE_FINISH,
					info);
			return;
		}

		try
		{
			File file = new File(downloadManager.getBasePath(), info.getName()
					+ ".a");
			if (file.exists())
			{
				file.delete();
				Log.v("lung", "delete old file");
			} else
			{
				file.createNewFile();
				info.setDownloadPath(file.getPath());
			}

			InputStream inputStream;
			FileOutputStream outputStream = new FileOutputStream(file);
			URL url = new URL(info.getDownloadUrl());
			HttpURLConnection httpURLConnection = (HttpURLConnection) url
					.openConnection();
			httpURLConnection.setConnectTimeout(120000);
			httpURLConnection.setReadTimeout(20000);

			// 获取下载文件的size
			totalSize = httpURLConnection.getContentLength();
			if (httpURLConnection.getResponseCode() == 404)
			{
				handler.post(new Runnable()
				{
					@Override
					public void run()
					{
						logger.e("lung", "下载出现错误");
						downloadManager.showToast(info.getName() + "下载出现错误");
					}
				});
				info.setState(DownloadInfo.STATE_ERROR);
				downloadManager.notifyDownloadStateEvent(
						DownloadInfo.STATE_ERROR, info);
				downloadManager.showToast(info.getName() + "下载出现错误");
				setCancel(true);
				throw new Exception("fail!");
			}

			// 检测sd卡剩下空间是否足够下载
			if (Util.getSDFreeSize() <= totalSize)
			{
				handler.post(new Runnable()
				{

					@Override
					public void run()
					{
						logger.e("lung", "空间不足");
						downloadManager.showToast(info.getName()
								+ "下载错误，磁盘空间不足");
						setCancel(true);
						info.setState(DownloadInfo.STATE_ERROR);
						downloadManager.notifyDownloadStateEvent(
								DownloadInfo.STATE_ERROR, info);
						return;
					}
				});
			}

			inputStream = httpURLConnection.getInputStream();
			byte buffer[] = new byte[1024 * 32];
			int readsize = 0;
			info.setDownloadSpeed("0 kB/s");
			info.setState(DownloadInfo.STATE_DOWNLOADING);
			info.setTotleSize(StringUtils.bytes2kb(totalSize));
			info.setHadDownloadSize(StringUtils.bytes2kb(0));
			// 设置下载数据
			setDownloadSpeed();

			while ((readsize = inputStream.read(buffer)) != -1 && !isCancel)
			{
				outputStream.write(buffer, 0, readsize);
				downloadSize += readsize;// 时时获取下载到的大小
				// Log.v("lung ", "下载进度 = "
				// + (int) ((downloadSize / (float) totalSize) * 100));
				// // publishProgress((int) ((downloadCount / (float) totalSize)
				// *
				// // 100));
			}
			if (downloadSize == totalSize)
			{
				info.setState(DownloadInfo.STATE_FINISH);
				File newFile = new File(downloadManager.getBasePath(),
						info.getName() + "." + info.getDownloadType());
				file.renameTo(newFile);
				downloadManager.notifyDownloadStateEvent(
						DownloadInfo.STATE_FINISH, info);
			}

			if (httpURLConnection != null)
			{
				httpURLConnection.disconnect();
			}
			inputStream.close();
			outputStream.close();
		} catch (Exception e)
		{
			e.printStackTrace();
			if (!isCancel)
			{
				handler.post(new Runnable()
				{

					@Override
					public void run()
					{
						logger.e("lung", "下载出现错误");
						downloadManager.showToast(info.getName() + "下载出现错误");
					}
				});
			}
			setCancel(true);
			info.setState(DownloadInfo.STATE_ERROR);
			downloadManager.notifyDownloadStateEvent(DownloadInfo.STATE_ERROR,
					info);

		}

	}

	/**
	 * 计算下载速度
	 */
	private void setDownloadSpeed()
	{
		if (info.getState() != DownloadInfo.STATE_DOWNLOADING)
		{
			return;
		}

		handler.postDelayed(new Runnable()
		{

			@Override
			public void run()
			{

				long size = downloadSize - lastDownloadSize;
				logger.v("Download", StringUtils.bytes2kb(size) + "/s");
				lastDownloadSize = downloadSize;
				info.setDownloadSpeed(StringUtils.bytes2kb(size) + "/s");
				info.setDownloadPercent((int) ((downloadSize / (float) totalSize) * 100));
				info.setHadDownloadSize(StringUtils.bytes2kb(downloadSize));
				downloadManager.notifyDownloadProgressEvent(
						(int) ((downloadSize / (float) totalSize) * 100), info);
				if (!isCancel)
				{
					setDownloadSpeed();
				}

			}
		}, 1000);

	}
}
